import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, FormInstance, Popconfirm } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProForm,
  ProFormDigit,
  ProFormRadio,
} from '@ant-design/pro-form';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import {
  removeRecognize,
  loadRecognize,
  getRecognize,
  addRecognize,
  updateRecognize,
} from './service';
import type { RecognizeBody, RecognizeListItem, RecognizeListPagination } from './data';
import CheckModule from '@/components/CheckModule';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: RecognizeBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updateRecognize({ ...fields }) : await addRecognize({ ...fields });
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: RecognizeListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRecognize(selectedRows.map((row) => row.recognizeId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const RecognizePage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<RecognizeListItem>();
  const [selectedRowsState, setSelectedRows] = useState<RecognizeListItem[]>([]);

  const columns: ProColumns<RecognizeListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '辨识名称',
      dataIndex: 'recognizeName',
      copyable: true,
    },
    {
      title: '排序',
      dataIndex: 'recognizeSort',
      tooltip: '越大越靠前',
      search: false,
      sorter: true,
      hideInDescriptions: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: false,
      valueEnum: {
        0: {
          text: '启用',
          status: 'Success',
        },
        1: {
          text: '禁用',
          status: 'Error',
        },
      },
    },

    {
      title: '辨识风险告知卡',
      // @ts-ignore
      span: 24,
      dataIndex: 'dangerNote',
      search: false,
      hideInTable: true,
      valueType: 'jsonCode',
    },
    {
      title: '辨识事故应急处置卡',
      // @ts-ignore
      span: 24,
      dataIndex: 'doTrouble',
      search: false,
      hideInTable: true,
      valueType: 'code',
    },
    {
      title: '任职条件',
      // @ts-ignore
      span: 24,
      dataIndex: 'jobRequire',
      search: false,
      hideInTable: true,
      valueType: 'code',
    },
    {
      title: '责任书',
      // @ts-ignore
      span: 24,
      dataIndex: 'letterLiability',
      search: false,
      hideInTable: true,
      valueType: 'code',
    },
    {
      title: '安全告知',
      // @ts-ignore
      span: 24,
      dataIndex: 'notification',
      search: false,
      hideInTable: true,
      valueType: 'code',
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            setCurrentRow(record);
            setEditMode(true);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          okButtonProps={{ danger: true }}
          title={`确认删除辨识：${record.recognizeName}?`}
          onConfirm={async () => {
            setCurrentRow(record);
            await handleRemove([record]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="删除"
          cancelText="取消"
        >
          <a href="#"> 删除 </a>
        </Popconfirm>,
      ],
    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);

  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{ content: '' }}>
        <ProTable<RecognizeListItem, RecognizeListPagination>
          headerTitle="辨识列表"
          actionRef={actionRef}
          rowKey="recognizeId"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setEditMode(false);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
          request={loadRecognize}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择{' '}
                <a
                  style={{
                    fontWeight: 600,
                  }}
                >
                  {selectedRowsState.length}
                </a>{' '}
                个辨识
              </div>
            }
          >
            <Popconfirm
              key="delete"
              title={`确认删除选中的${selectedRowsState.length}个辨识?`}
              okButtonProps={{ danger: true }}
              onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <Button danger>批量删除</Button>
            </Popconfirm>
            {/*<Button type="primary">批量审批</Button>*/}
          </FooterToolbar>
        )}
        <ModalForm<RecognizeBody>
          title={currentRow?.recognizeId || 0 > 0 ? '编辑辨识' : '新建辨识'}
          // width="400px"
          formRef={formRef}
          modalProps={{destroyOnClose: true, maskClosable: false}}
          visible={createModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          onFinish={async (value) => {
            const success = await handleAdd(value, editMode);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          request={(params) => {
            if (params.recognizeId > 0) {
              return getRecognize(params).then(({ data }) => {
                return data;
              });
            } else {
              return new Promise<RecognizeBody>((resolve, reject) => {
                resolve({
                  recognizeId: 0,
                  recognizeName: '',
                  recognizeSort: 0,
                  status: '0',
                  dangerNote: '',
                  doTrouble: '',
                  jobRequire: '',
                  letterLiability: '',
                  notification: '',
                  createTime: '',
                });
              });
            }
          }}
          params={{ ...currentRow }}
        >
          <ProFormText hidden name="recognizeId" />
          <ProForm.Group>
            <ProFormText
              rules={[
                {
                  required: true,
                  message: '辨识名称为必填项',
                },
              ]}
              label={'辨识名称'}
              name="recognizeName"
              width={'lg'}
            />
            <ProFormDigit
              tooltip={'越大越靠前'}
              rules={[
                {
                  required: true,
                  message: '排序不能为空',
                },
              ]}
              width={'xs'}
              label={'排序'}
              name="recognizeSort"
            />
            <ProFormRadio.Group
              name="status"
              label="状态"
              options={[
                {
                  label: '启用',
                  value: '0',
                },
                {
                  label: '禁用',
                  value: '1',
                },
              ]}
            />
          </ProForm.Group>

          <ProFormTextArea label={'辨识风险告知卡'} name="dangerNote" />
          <ProFormTextArea label={'辨识事故应急处置卡'} name="doTrouble" />
          <ProFormTextArea label={'任职条件'} name="jobRequire" />
          <ProFormTextArea label={'责任书'} name="letterLiability" />
          <ProFormTextArea label={'安全告知'} name="notification" />
        </ModalForm>

        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.recognizeName && (
            <ProDescriptions<RecognizeBody>
              column={2}
              bordered={true}
              title={currentRow?.recognizeName}
              request={getRecognize}
              layout={'vertical'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<RecognizeBody>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default RecognizePage;
